// app/controller/upload.js

const Controller = require('egg').Controller;
const XLSX = require('xlsx');

class UploadExcelController extends Controller {
    async index() {
        const { ctx } = this;
        const file = ctx.request.files[0]; // 获取上传的文件
        if (!file) {
            ctx.body = { error: 'No file uploaded.' };
            return;
        }

        const reader = fs.createReadStream(file.path);
        const workbook = XLSX.read(reader, { type: 'stream' });
        const sheetName = workbook.SheetNames[0]; // 获取第一个工作表名称
        const worksheet = workbook.Sheets[sheetName];

        // 将工作表转换为JSON数组
        const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });

        // 将JSON数组转换为以列头为key，行单元格为value的数组
        const transformedData = jsonData.map((row) => {
            const obj = {};
            Object.keys(row).forEach((key, index) => {
                obj[row[key]] = row[key + 1]; // 假设列头在第一行，数据从第二行开始
            });
            return obj;
        });

        // 清理临时文件
        fs.unlinkSync(file.path);

        ctx.body = transformedData;
    }
}

module.exports = UploadExcelController;